﻿namespace HelperLibrary;

/// <summary>
/// 软授权认证
/// </summary>
public class SoftwareAuthorization
{
    /// <summary>
    /// 授权码
    /// </summary>
    private static string sn = string.Empty;
    /// <summary>
    /// 授权结果
    /// </summary>
    private static SFAuthModel authModel { get; set; }
    /// <summary>
    /// 获取软授权认证
    /// </summary>
    /// <returns></returns>
    public static SFAuthModel GetAuth()
    {
        if (string.IsNullOrEmpty(sn))
        {
            sn = GetSN();
        }
        if (authModel == null)
        {
            authModel = new SFAuthModel();
            authModel.status = AVCKey.AVCKey_VerifyAuthCode(sn);
            authModel.type = AVCKey.AVCKey_GetAuthCodeProductType(sn);
            byte[] datebytes = new byte[10];
            bool result = AVCKey.AVCKey_GetAuthCodeExpireDate(sn, datebytes);
            if (result)
            {
                authModel.expiredate = Encoding.UTF8.GetString(datebytes);
            }
            else
            {
                authModel.expiredate = DateTime.Now.ToString("yyyy-MM-dd");
            }
        }
        return authModel;
    }

    /// <summary>
    /// 获取授权文件
    /// </summary>
    /// <returns></returns>
    private static string GetSN()
    {
        string sn = null;
        try
        {
            string path = Path.Combine(AppContext.BaseDirectory, "sn.cfg");
            using (StreamReader sr = new StreamReader(path, false))
            {
                sn = sr.ReadLine().ToString();
            }
        }
        catch
        {
            throw new Exception($"授权许可数据文件获取失败");
        }
        return sn;
    }
}

/// <summary>
/// 授权模型
/// </summary>
public class SFAuthModel
{
    /// <summary>
    /// 授权状态（小于0授权异常）
    /// </summary>
    public int status { get; set; }

    /// <summary>
    /// 产品类型（29：AI无感知心理测评管理系统）
    /// </summary>
    public int type { get; set; }

    /// <summary>
    /// 有效日期（yyyy-MM-dd）
    /// </summary>
    public string expiredate { get; set; }
}
